package top.saplf.sileny.base

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Bitmap
import com.bumptech.glide.Glide
import com.bumptech.glide.request.FutureTarget
import com.bumptech.glide.signature.StringSignature
import top.saplf.sileny.SilenyApplication
import top.saplf.sileny.ext.writeSingle
import top.saplf.sileny.util.async
import top.saplf.sileny.util.displayHeight
import top.saplf.sileny.util.displayWidth

/**
 * @author Saplf on 17/4/8
 */
object SettingManager {
    private val app: Application by lazy { SilenyApplication.app }

    private val splashBitmapKey by lazy { "splashBitmap" }

    // 通用配置
    private val generalStore: SharedPreferences by lazy { app.getSharedPreferences("general", Context.MODE_PRIVATE) }
    private var splashUrlCache = ""
    private val splashUrl: String
        get() {
            splashUrlCache = "https://unsplash.it/$displayWidth/$displayHeight/?random&hash=${System.currentTimeMillis()}"
            return splashUrlCache
        }

    private var requesting = false
    fun getSplashBackground(): String = generalStore.getString(splashBitmapKey, "")
    fun refreshSplashBitmap() {
        if (!requesting) {
            requesting = true
            async {
                val result: FutureTarget<Bitmap> = Glide
                        .with(app.applicationContext)
                        .load(splashUrl)
                        .asBitmap()
                        .signature(StringSignature(splashUrl))
                        .into(displayWidth, displayHeight)
                if (result.get() != null) {
                    generalStore.writeSingle { splashBitmapKey to splashUrlCache }
                }
                requesting = false
            }
        }
    }
}